package ru.autofan.domain;

import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToMany;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
import javax.persistence.Table;

@Entity
@Table(name = "user")
public class User implements Serializable {

	private static final long serialVersionUID = 1L;

	@Id
	@GeneratedValue(strategy = GenerationType.AUTO)
	private Long id;

	@Column(name = "email", unique = true)
	private String email;

	@Column(name = "upassword")
	private String uPassword;

	@Column(name = "code")
	private String code;

	@Column(name = "roles")
	@OneToMany(fetch = FetchType.LAZY, mappedBy = "owner", cascade = CascadeType.ALL)
	private Set<Car> cars;

	@Column(name = "roles")
	@ManyToMany(fetch = FetchType.LAZY)
	private Set<Role> roles;

	@Column(name = "personal_info", nullable = false)
	@OneToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
	private UserPersonalInfo personalInfo;

	public Long getId() {
		return id;
	}

	public void setId(Long id) {
		this.id = id;
	}

	public String getCode() {
		return code;
	}

	public void setCode(String code) {
		this.code = code;
	}

	public String getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}

	public String getUPassword() {
		return uPassword;
	}

	public void setUPassword(String password) {
		uPassword = password;
	}

	public Set<Role> getRoles() {
		if (roles == null) {
			roles = new HashSet<Role>();
		}
		return roles;
	}

	public Set<Role> cloneRoles() {
		Set<Role> set = new HashSet<Role>(getRoles().size());
		for (Role role : getRoles()) {
			try {
				set.add((Role)role.clone());
			} catch (CloneNotSupportedException e) {
				e.printStackTrace();
			}
		}
		return set;
	}

	public String getName() {
		return getPersonalInfo().getFirstName() + " "
				+ getPersonalInfo().getLastName();
	}

	public void setRoles(Set<Role> roles) {
		this.roles = roles;
	}

	public UserPersonalInfo getPersonalInfo() {
		return personalInfo;
	}

	public void setPersonalInfo(UserPersonalInfo personalInfo) {
		this.personalInfo = personalInfo;
	}

	public Set<Car> getCars() {
		return cars;
	}

	public void setCars(Set<Car> cars) {
		this.cars = cars;
	}
}
